# -*- coding:utf-8 -*- 

import web
import urllib2
import traceback
import json
from utils import DbSession
from Commplugin import MonitorTask
from utils import getcurrdatestr
from pager import Pager

name = "HTTP"

class HttpCheck(object):


    def GET(self,name):
        support_method = ["getHttpList"]
        if not name in support_method:
            return 'No right to GET() access ' + name + '!'
        try:
            func = getattr(self, name)
            return func()
        except Exception,e:
            return "Error: %s" % e

    def POST(self,name):
        return "not implemented!"

    def extractdescr(self, rec):
        srvid = rec[0]
        srvtype = rec[1]
        srvdescr = json.loads(rec[2])
        srvretrycount = rec[6] 

        srvdescr["id"] = srvid
        srvdescr["servicestatus"] = rec[3]
        srvdescr["checkinterval"] = rec[4]
        srvdescr["retrycount"] = srvretrycount
        srvdescr["servicetype"] = srvtype

        return srvtype, srvdescr

    def getHttpList(self):
        render = web.template.render('html')
        with DbSession() as session:
            total = session.getCount("select count(1) from m_services where service_type='%s'" % name)
            sql="select * from m_services where service_type='%s' order by id asc limit 0,5" % name
            allservice = session.selectall(sql)
            data = []
            for srv in allservice:
                srvtype, srvdescr = self.extractdescr(srv)
                data.append(srvdescr)
            pages=Pager(url='/monitorhttp_list.html?=%s',total_count=total,page_size=4,cur_page=1).getPage()
            return render.monitorhttp_list(pages,data)    

class HttpCheckTask(MonitorTask):
    '''
    @param alarm alarm instance
    @param context service description
    '''
    def __init__(self, alarm, scheduler, context):
        MonitorTask.__init__(self, alarm, scheduler, context)

    def docheck(self):
        print("start execute http task for %s" % self.context["url"])
        url = self.context["url"]
        timeout = self.context["timeout"]
        retrycount = int(self.context["retrycount"])
        for retryindex in range(retrycount):
            try:
                try:
                    response = urllib2.urlopen(url, timeout = timeout)
                    retcode = response.getcode()
                except:
                    retcode = -1

                if retcode == 200:
                    if not self.isrunning():
                        self.updatestatus("RUNNING")
                    break
                else:
                    if retryindex == retrycount-1:
                        servicename = self.context["servicetype"]
                        url = self.context["url"]
                        now = getcurrdatestr()

                        alarminfo = "service %s STOP, url=%s, STOP TIME=%s" % (
                                servicename, url, now        
                                )
                        
                        if not self.isstoped():
                            '''send alarm if service_status is not STOP'''
                            self.firealarm(alarminfo)
            except:
                traceback.print_exc()
